#include <func.h>
#include "head.h"
#include "taskQueue.h"
#define STR_LEN 8
//打印当前目录
int printWorkingDir(task_t* pTask){
    
    //printf("current working directory: %s\n",buf);
    send(pTask->netFd,pTask->nowPath,strlen(pTask->nowPath),0);
}
//创建文件夹
int myMkdir(task_t *pTask){
    char *command = strtok(pTask->buf," ");//解析获取命令
    char *dirName = strtok(NULL," ");//解析获取文件名
    MYSQL *db = pTask->db;
    //找到当前路径的preId
    char sql[300] = "select id from file where phyAddress = '";
    //sprintf(sql,"select preId from file where phyAddress = '%s';",pTask->nowPath);
    strcat(sql,pTask->nowPath);
    strcat(sql,"'");
    puts(sql);
    int qret = mysql_query(db,sql);
    MYSQL_RES *result = mysql_store_result(db);
    MYSQL_ROW row = mysql_fetch_row(result);//取出id row[0]

    char newPath[300] = {0};
    strcat(newPath,pTask->nowPath);
    strcat(newPath,"/");
    strcat(newPath,dirName);
    char sql2[300] = "insert into file(fileName,preId,type,userName,phyAddress) values('";
    strcat(sql2,dirName);
    strcat(sql2,"',");
    strcat(sql2,row[0]);
    strcat(sql2,",'d','");
    strcat(sql2,pTask->userName);
    strcat(sql2,"','");
    strcat(sql2,newPath);
    strcat(sql2,"')");
    puts(sql2);
    qret = mysql_query(db,sql2);
    
    if(qret != 0){
        printf("Error: %s\n", mysql_error(db));
        exit(-1);
    }
    return 0;
}
//删除文件夹
int myRmdir(task_t *pTask){
    char *command = strtok(pTask->buf," ");//解析获取命令
    char *fileName = strtok(NULL," ");//解析获取文件名
    MYSQL *db = pTask->db;
    char sql[4096] = {0};
    sprintf(sql,"select id from file where fileName = '%s' and userName = '%s'",fileName,pTask->userName);
    puts(sql);
    int qret = mysql_query(db,sql);
    MYSQL_RES *result = mysql_store_result(db);
    if(mysql_num_rows(result)==0){
        send(pTask->netFd,"no such directory",18,0);
        return 0;
    }
    MYSQL_ROW row = mysql_fetch_row(result);//取出id
    strcpy(pTask->fileId,row[0]);
    char sql2[4096] = {0};
    sprintf(sql2,"delete from file where id = %s",row[0]);
    puts(sql2);
    qret = mysql_query(db,sql2);
    DFSrmdir(pTask);
    send(pTask->netFd,"delete success",15,0);
    mysql_free_result(result);
    return 0;
}
//递归删除子目录及文件
int DFSrmdir(task_t *pTask){
    MYSQL *db = pTask->db;
    char sql[4096] = {0};
    sprintf(sql,"select id from file where preId = %s",pTask->fileId);
    puts(sql);
    int qret = mysql_query(db,sql);
    MYSQL_RES *result = mysql_store_result(db);
    MYSQL_ROW row;// //取出子文件夹及文件的id
    while ((row = mysql_fetch_row(result)) != NULL)
    {
        for(int i = 0; i < mysql_num_fields(result); ++i){
            //printf("%s\t", row[i]);
            char sql2[4096] = {0};
            sprintf(sql2,"delete from file where id = %s",row[i]);
            puts(sql2);
            qret = mysql_query(db,sql2);
            strcpy(pTask->fileId,row[i]);
            DFSrmdir(pTask);
        }
        //printf("\n");
    }
}
//删除文件
int removeFile(task_t* pTask){
    char *command = strtok(pTask->buf," ");//解析获取命令
    char *fileName = strtok(NULL," ");//解析获取文件名
    //remove(fileName);
    MYSQL *db = pTask->db;
    char sql[4096] = {0};
    sprintf(sql,"select id from file where fileName = '%s' and userName = '%s' and phyAddress='%s'"
    ,fileName,pTask->userName,pTask->nowPath);
    puts(sql);
    int qret = mysql_query(db,sql);
    MYSQL_RES *result = mysql_store_result(db);
    if(mysql_num_rows(result)==0){
        send(pTask->netFd,"no such file",13,0);
        return 0;
    }
    MYSQL_ROW row = mysql_fetch_row(result);//取出id

    char sql2[4096] = {0};
    sprintf(sql2,"delete from file where id = %s",row[0]);
    puts(sql2);
    qret = mysql_query(db,sql2);
    send(pTask->netFd,"delete success",15,0);
    mysql_free_result(result);
    return 0;
}

//显示当前目录内容，返回字符串result
int ls(task_t *pTask) {
    MYSQL *db = pTask->db;
    //找到当前路径的Id
    //char sql[300] = "select id from file where phyAddress = '";
    char sql[4096] = {0};
    sprintf(sql,"select id from file where phyAddress = '%s';",pTask->nowPath);
    // strcat(sql,pTask->nowPath);
    // strcat(sql,"'");
    puts(sql);
    int qret = mysql_query(db,sql);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(db));
        exit(-1);
    }
    MYSQL_RES *result = mysql_store_result(db);
    MYSQL_ROW row = mysql_fetch_row(result);//取出preId row[0]

    char sql2[4096] = {0};
    sprintf(sql2,"select fileName from file where userName = '%s' and preId = %s;",pTask->userName,row[0]);
    puts(sql2);
    qret = mysql_query(db,sql2);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(db));
        exit(-1);
    }
    MYSQL_RES *result2 = mysql_store_result(db);
    MYSQL_ROW row2;
    char lsbuf[1024] = {0};
    while ((row2 = mysql_fetch_row(result2)) != NULL)
    {
        for(int i = 0; i < mysql_num_fields(result); ++i){
            strcat(lsbuf,row2[i]);
            strcat(lsbuf," ");
        }
        printf("\n");
    }
    puts(lsbuf);
    send(pTask->netFd,lsbuf,strlen(lsbuf),0);
    mysql_free_result(result);
    mysql_free_result(result2);
}
//切换目录
// int cd(task_t *pTask){
//     char *command = strtok(pTask->buf," ");//解析获取命令
//     char *fileName = strtok(NULL," ");//解析获取文件名
//     chdir(fileName);
//     printWorkingDir(pTask);
//     return 0;
// }
int cd(task_t *pTask) {

    char s[1024] = {0};
    strcpy(s, pTask->buf);
    char *w = strtok(s, " ");
    char orderName[512] = {0};
    char destPath[512] = {0};
    strcpy(orderName, w);
    if ((w = strtok(NULL, " ")) != NULL) {
        strcpy(destPath, w);
        puts(destPath);
    }
    
    if (!strcmp(destPath, "-")) //返回上次目录
    {
        if (strlen(pTask->prePath) == 0) {
            char s[1024] = {0};
            strcpy(s, "cd :OLDPWD未设定");
            send(pTask->netFd, s, strlen(s), 0);
            return -1;
        }
        else {
            char temp[1024] = {0};
            //char *oldpath = getcwd(NULL, 0);
            strcpy(temp,pTask->nowPath);//先保存当前路径
            strcpy(pTask->nowPath,pTask->prePath);
            strcpy(pTask->prePath, temp);
            send(pTask->netFd, pTask->nowPath, strlen(pTask->nowPath), 0);
        }
    }
    else if (strlen(destPath) == 0 || !strcmp(destPath, "~"))//返回家目录
    {
        char temp[1024] = {0};
        strcpy(temp,pTask->nowPath);//先保存当前路径
        memset(pTask->nowPath,0,sizeof(pTask->nowPath));
        sprintf(pTask->nowPath,"/%s",pTask->userName);
        strcpy(pTask->prePath,temp);
        send(pTask->netFd, pTask->nowPath, strlen(pTask->nowPath), 0);
    }
    else if(!strcmp(destPath, "."))//切换当前目录
    {
        send(pTask->netFd, pTask->nowPath, strlen(pTask->nowPath), 0);
    }
    else if(!strcmp(destPath, ".."))//切换上级目录
    {
        MYSQL *db = pTask->db;
        //找到当前路径的preId
        //char sql[300] = "select preId from file where phyAddress = '";
        char sql[4096] = {0};
        sprintf(sql,"select preId from file where phyAddress = '%s';",pTask->nowPath);
        // strcat(sql,pTask->nowPath);
        // strcat(sql,"'");
        puts(sql);
        int qret = mysql_query(db,sql);
        MYSQL_RES *result = mysql_store_result(db);
        MYSQL_ROW row = mysql_fetch_row(result);//取出preId row[0]
        if(strcmp(row[0],"0") == 0){
            send(pTask->netFd, pTask->nowPath, strlen(pTask->nowPath), 0);
            return 0;
        }
        char sql2[300] = "select phyAddress from file where id = ";
        //sprintf(sql2,"select phyAdress from file where id = %s",row[0]);
        strcat(sql2,row[0]);
        puts(sql2);
        qret = mysql_query(db,sql2);
        MYSQL_RES *result2 = mysql_store_result(db);
        MYSQL_ROW row2 = mysql_fetch_row(result2);//取出路径

        char temp[1024] = {0};
        strcpy(temp,pTask->nowPath);//先保存当前路径
        memset(pTask->nowPath,0,sizeof(pTask->nowPath));
        strcpy(pTask->nowPath,row2[0]);
        strcpy(pTask->prePath,temp);//把之前的路径存进prePath
        send(pTask->netFd, pTask->nowPath, strlen(pTask->nowPath), 0);
        mysql_free_result(result);

    }
    else {//切到指定路径
        puts(destPath);
        //查询该路径是否属于该用户，如果不属于则不可跳转
        //select user from file where phyAddress = 'destPath';
        MYSQL *db=pTask->db;
        //char sql[300] = "select userName from file where phyAddress = '";
        char sql[4096] = {0};
        sprintf(sql,"select userName from file where phyAddress = '%s%s%s';",pTask->nowPath,"/",destPath);
        // strcat(sql,pTask->nowPath);
        // strcat(sql,"/");
        // strcat(sql,destPath);
        // strcat(sql,"'");
        puts(sql);
        int qret = mysql_query(db,sql);
        MYSQL_RES *result = mysql_store_result(db);
        if(mysql_num_rows(result)==0){
            send(pTask->netFd,"no such directory",18,0);
            return 0;
        }
        MYSQL_ROW row = mysql_fetch_row(result);//取出userName row[0]

        if(strcmp(row[0],pTask->userName) != 0){
            send(pTask->netFd,"Do not have permission",23,0);
            return 0;
        }
        else{
            char temp[1024] = {0};
            strcpy(temp,pTask->nowPath);//先保存当前路径
            strcat(pTask->nowPath,"/");
            strcat(pTask->nowPath,destPath);
            strcpy(pTask->prePath,temp);
            send(pTask->netFd, pTask->nowPath, strlen(pTask->nowPath), 0);
        }
        mysql_free_result(result);
        
    }
    return 0;
}
//下载文件
int downloadFile(task_t *pTask){
    //gets file1
     char *command = strtok(pTask->buf," ");//解析获取命令
    char *fileName = strtok(NULL," ");//解析获取文件名
    int length = strlen(fileName);
    
    //首先判断文件是否存在,文件存在是传输文件的必要条件！ 
    DIR *pdir = opendir(".");
    ERROR_CHECK(pdir, NULL, "open");
    struct dirent *pdirent;
    while ((pdirent = readdir(pdir)) != NULL) {
        if(!strcmp(pdirent->d_name, fileName)) {
            break;
        }
    }
    if ((pdirent = readdir(pdir)) == NULL) {
        puts("No such file or directory!");
        send(pTask->netFd, "No such file or directory!", 26, 0);
        return -1;
    }

    char offset[100]={0};
    recv(pTask->netFd,offset,100,0);//接收客户端发来的客户端本地文件的大小，也就是偏移量
    //服务端再把字符串类改回long类型
    long offsetLen=atoi(offset);//偏移量也有可能是0
    //printf("pianyilen = %d\n",pianyilen);

    train_t t;
    bzero(t.buf,sizeof(t.buf));
    t.dataLength = length;
    strcpy(t.buf,fileName);

    printf("length = %d,fileName = %s\n",length,fileName);
    
    int fd = open(fileName, O_RDWR);
    ERROR_CHECK(fd,-1,"open");
    // int ret = send(pTask->netFd,&t,sizeof(t.dataLength)+ t.dataLength,MSG_NOSIGNAL);//发送文件名
    // ERROR_CHECK(ret,-1,"send");
    //不再需要发送文件名，客户端自己获取
    //获取服务器文件总大小并发送
    struct stat statbuf;
    int ret = fstat(fd,&statbuf);//获取文件的总大小
    ERROR_CHECK(ret,-1,"fstat");
    t.dataLength = sizeof(statbuf.st_size);//把文件的大小装入小火车
    memcpy(t.buf,&statbuf.st_size,sizeof(statbuf.st_size));
    send(pTask->netFd,&t,sizeof(t.dataLength)+t.dataLength,MSG_NOSIGNAL);

    //对比进行判断
    long totalFileLen = statbuf.st_size;
    printf("offsrtLen = %ld,totallen = %ld\n",offsetLen,totalFileLen);
    if (offsetLen < totalFileLen) {
        lseek(fd, offsetLen, SEEK_SET);
    }
    else {
        //printf("Recv success!\n");
        return 0;
    }

    char *p = (char *)mmap(NULL,statbuf.st_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    ERROR_CHECK(p,MAP_FAILED,"mmap");
    off_t total = offsetLen;
    while(total < statbuf.st_size){
        if(statbuf.st_size - total < sizeof(t.buf)){
            //最后一次发送
            t.dataLength = statbuf.st_size-total;
        }
        else{
            t.dataLength = sizeof(t.buf);
        }
        memcpy(t.buf,p+total,t.dataLength);//把数据装入火车车厢
        int ret = send(pTask->netFd,&t,sizeof(t.dataLength)+t.dataLength,MSG_NOSIGNAL);
        ERROR_CHECK(ret,-1,"send");
        total += t.dataLength;
    }
    munmap(p,statbuf.st_size);
    t.dataLength = 0;
    send(pTask->netFd,&t,sizeof(t.dataLength),0);
    //发送终止
    close(fd);
}
//上传文件
int recvn(int netFd,void *p, int n){
    int total = 0;
    int ret;
    char *pTmp = (char *)p;
    while(total < n){
        ret = recv(netFd,pTmp+total,n-total,0);
        ERROR_CHECK(ret,-1,"recv");
        total+= ret;
    }
    return 0;
}
int uploadFile(task_t *pTask){
    int dataLength;
    char name[1024] = {0};
    int ret =recvn(pTask->netFd,&dataLength,sizeof(int));//先收火车头
    ERROR_CHECK(ret,-1,"recv");
    ret = recvn(pTask->netFd,name, dataLength);//再收文件名
    ERROR_CHECK(ret,-1,"recv file");
    char md[1024] = {0}; 
    ret =recvn(pTask->netFd,&dataLength,sizeof(int));//先收火车头
    ERROR_CHECK(ret,-1,"recv");
    ret = recvn(pTask->netFd,md, dataLength);//再收md值
    ERROR_CHECK(ret,-1,"recv md5");
    
    MYSQL *db = pTask->db;
    //首先获得当前目录的id作为文件的preid
    //select id from myNetDisk where phyaddr='pTask->nowPath';
    char sql[4096] = {0};
    sprintf(sql,"select id from file where phyAddress = '%s'",pTask->nowPath);
    puts(sql);
    int qret = mysql_query(db,sql);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(db));
        exit(-1);
    }
    MYSQL_RES *result = mysql_store_result(db);
    MYSQL_ROW row = mysql_fetch_row(result);
    puts("------当前目录id----------");
    puts(row[0]);
    //将获得的md值与数据库内的mdkey比较，如果没有就上传实际文件与逻辑文件
    //如果存在该文件就只上传逻辑文件，实现秒传功能
    char sql1[4096] = {0};
    sprintf(sql1,"select * from file where md5 = '%s'",md);
    puts(sql1);
    qret = mysql_query(db,sql1);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(db));
        exit(-1);
    }
    MYSQL_RES *result1 = mysql_store_result(db);
    MYSQL_ROW row1 = mysql_fetch_row(result1);
    if(row1 == NULL){//没有对应的文件
        puts("No such file,please upload");
        goto next;
    }
    else{
        char sql2[4096] = {0};
        sprintf(sql2,"select userName from file where md5 = '%s'",md);
        puts(sql2);
        qret = mysql_query(db,sql2);
        if(qret != 0){
            printf("Error: %s\n", mysql_error(db));
            exit(-1);
        }
        MYSQL_RES *result2 = mysql_store_result(db);
        MYSQL_ROW row2 = mysql_fetch_row(result2);
        for(int i = 0; i < mysql_num_fields(result); ++i){
            //printf("%s\t", row[i]);
            if(strcmp(pTask->userName,row2[i]) == 0){//对比md5对应的文件的用户名，如果不一样直接秒传，一样继续往下对比
                // send(pTask->netFd,"3",2,0);
                // return 3;
                char sql4[4096] = {0};
                sprintf(sql4,"select fileName from file where md5 = '%s'",md);
                puts(sql4);
                qret = mysql_query(db,sql4);
                if(qret != 0){
                    printf("Error: %s\n", mysql_error(db));
                    exit(-1);
                }
                MYSQL_RES *result4 = mysql_store_result(db);
                MYSQL_ROW row4 = mysql_fetch_row(result4);
                for(int i = 0; i < mysql_num_fields(result); ++i){//对比md5对应的文件的文件名，如果不一样直接秒传，一样继续往下对比
                    if(strcmp(name,row4[i]) == 0){
                        char sql6[4096] = {0};
                        sprintf(sql6,"select phyAddress from file where md5 = '%s'",md);
                        puts(sql6);
                        qret = mysql_query(db,sql6);
                        if(qret != 0){
                            printf("Error: %s\n", mysql_error(db));
                            exit(-1);
                        }
                        MYSQL_RES *result6 = mysql_store_result(db);
                        MYSQL_ROW row6 = mysql_fetch_row(result6);
                        for(int i = 0; i < mysql_num_fields(result); ++i){
                            if(strcmp(pTask->nowPath,row6[i]) == 0){
                                send(pTask->netFd,"3",2,0);
                                return 3;
                            }
                            else{
                                char sql7[4096] = {0};
                                sprintf(sql7,"insert into file(fileName,preId,type,userName,phyAddress,md5) values('%s','%s','f','%s','%s','%s')",
                                name,row[0],pTask->userName,pTask->nowPath,md);
                                puts(sql7);
                                qret = mysql_query(db,sql7);
                                if(qret != 0){
                                    printf("Error: %s\n", mysql_error(db));
                                    exit(-1);
                                }
                                send(pTask->netFd,"2",2,0);
                                return 2;
                            }
                        }
                    }
                    else{
                        char sql5[4096] = {0};
                        sprintf(sql5,"insert into file(fileName,preId,type,userName,phyAddress,md5) values('%s','%s','f','%s','%s','%s')",
                        name,row[0],pTask->userName,pTask->nowPath,md);
                        puts(sql5);
                        qret = mysql_query(db,sql5);
                        if(qret != 0){
                            printf("Error: %s\n", mysql_error(db));
                            exit(-1);
                        }
                        send(pTask->netFd,"2",2,0);
                        return 2;
                    }
                }

            }
            else{
                char sql3[4096] = {0};
                sprintf(sql3,"insert into file(fileName,preId,type,userName,phyAddress,md5) values('%s','%s','f','%s','%s','%s')",
                name,row[0],pTask->userName,pTask->nowPath,md);
                puts(sql3);
                qret = mysql_query(db,sql3);
                if(qret != 0){
                    printf("Error: %s\n", mysql_error(db));
                    exit(-1);
                }
                send(pTask->netFd,"2",2,0);
                return 2;
            }
        }
    }
    next:
        send(pTask->netFd,"1",2,0);//发送信号给客户端
        int fd = open(name, O_RDWR|O_CREAT, 0666);
        ERROR_CHECK(fd,-1,"open");
        char buf[1024] = {0};
        long fileSize;
        recvn(pTask->netFd,&dataLength,sizeof(int));//先收火车头
        recvn(pTask->netFd,&fileSize,sizeof(fileSize));//再收文件长度
        printf("fileSize = %ld\n", fileSize);
        //ftruncate(fd,fileSize);
        off_t downSize = 0;
        off_t lastSize = 0;
        off_t slice = fileSize/1000;
        struct timeval begTime,endTime;
        gettimeofday(&begTime,NULL);
        while(1){
            ret = recvn(pTask->netFd,&dataLength,sizeof(int));//先收火车头
            ERROR_CHECK(ret,-1,"recv");
            if(dataLength==0){
                break;
            }
            if(dataLength != 1000){
                printf("dataLength = %d\n", dataLength);
            }
            ret = recvn(pTask->netFd,buf,dataLength);
            ERROR_CHECK(ret,-1,"recv");
            downSize += dataLength;
            if(downSize-lastSize > slice){
                printf("%5.2lf%s\r", 100.0*downSize/fileSize,"%");
                fflush(stdout);
                lastSize = downSize;
            }
            write(fd,buf,dataLength);
        }
        printf("100.00%s\n", "%");
        gettimeofday(&endTime,NULL);
        printf("total time = %ld us\n", 1000000*(endTime.tv_sec-begTime.tv_sec) + endTime.tv_usec-begTime.tv_usec);
        //上传完毕后 数据库也插入一个逻辑文件
        char sql8[4096] = {0};
        sprintf(sql8,"insert into file(fileName,preId,type,userName,phyAddress,md5) values('%s','%s','f','%s','%s','%s')",
        name,row[0],pTask->userName,pTask->nowPath,md);
        puts(sql8);
        qret = mysql_query(db,sql8);
        if(qret != 0){
            printf("Error: %s\n", mysql_error(db));
            exit(-1);
        }
        //send(pTask->netFd,"4",2,0);
        return 0;


}

int getSalt(char *salt, char *serctNum)
{   //老师文件里自带的函数
    int i, j;
    for(i = 0, j = 0; serctNum[i] && j != 3; ++i)
    {
        if(serctNum[i] == '$')
        {
            ++j;
        }
    }
    strncpy(salt, serctNum, i - 1);
    return 0;
}

int checkUserPass(task_t *pTask)
{   
    struct spwd* spwd;
    //#include <shadow.h>  改etc/shadow文件为权限666
    if((spwd = getspnam(pTask->userName)) == NULL){
        puts("解析密文错误");
        return -1;
    }
    //puts(spwd->sp_pwdp);
    char salt[20] = {0};
    //将密文中的salt取出,spwd->sp_pwdp是密文
    getSalt(salt, spwd->sp_pwdp);//把密文前8位取出来
    //将储存密文和用户输入的密码与salt生成的密文对比
    //相同则密码正确，返回0；不正确返回-1
    //crypt 头文件、宏、-lcrypt
    //puts("here");
    if(strcmp(spwd->sp_pwdp, crypt(pTask->password, salt)) != 0)
    {
        return -1;
    }
    //puts("good");
    return 0;
}

void usrConnectRecord(task_t *pTask){
    //task_t myTask = *pTask;
    time_t now = time(NULL);
    struct tm * pTm = localtime(&now); 
    syslog(LOG_INFO,"user = %s netFd=%d %s %02d%02d %02d:%02d:%02d\n",pTask->userName,pTask->netFd,"connect time:",pTm->tm_mon+1,
    pTm->tm_mday,pTm->tm_hour,pTm->tm_min,pTm->tm_sec); 
}
void usrCommandRecord(task_t *pTask){
    //task_t myTask = *pTask;
    syslog(LOG_INFO,"user = %s netFd=%d %s %s\n",pTask->userName,pTask->netFd,"command:",pTask->buf); 
    puts(pTask->buf);
}
//数据库初始化
int mysqlInit(task_t *pTask){
    MYSQL *db = mysql_init(NULL);//自动分配，初始化一个MYSQL对象
    pTask->db = db;
    char *host = "localhost";
    char *user = "root";
    char *mysqlpassword = "123";
    char *database = "liguohao";
    MYSQL *ret = mysql_real_connect(db,host,user,mysqlpassword,database,0,NULL,0);
    if(ret != NULL){
        memset(pTask->nowPath,0,sizeof(pTask->nowPath));
        strcpy(pTask->nowPath,"/");//task获得当前用户逻辑目录路径
        strcat(pTask->nowPath,pTask->userName);
        printf("connect success\n");
    }
    else{
        printf("Error: %s\n",mysql_error(db));
        exit(-1);
    }
}
//登录
int login(task_t *pTask){
    //mysql_close(db);
    MYSQL *db = pTask->db;
    char sql[300] = "select ciphertext from user where userName = '";
    strcat(sql,pTask->userName);
    strcat(sql,"'");
    int qret = mysql_query(db,sql);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(db));
        exit(-1);
    }
    MYSQL_RES *result = mysql_store_result(db);
    printf("the row number = %lld\n", mysql_num_rows(result));
    MYSQL_ROW row;
    char mysqlbuf[1024] = {0};
    if ((row = mysql_fetch_row(result)) != NULL)
    {
        //for(int i = 0; i < mysql_num_fields(result); ++i){
            strcpy(mysqlbuf,row[0]);
    }
    else{
        return -1;
    }
    
    
    row = mysql_fetch_row(result);
    //struct spwd* spwd;
    //char salt[20] = {0};
    //将密文中的salt取出,spwd->sp_pwdp是密文
    getSalt(pTask->salt, mysqlbuf);//把密文前8位取出来
    //将储存密文和用户输入的密码与salt生成的密文对比
    //相同则密码正确，返回0；不正确返回-1
    //crypt 头文件、宏、-lcrypt
    //puts("here");
    if(strcmp(mysqlbuf, crypt(pTask->password, pTask->salt)) != 0)
    {
        return -1;
    }
    //puts("good");
    return 0;
    mysql_free_result(result);
    //mysql_close(db);
}
//注册
int myRegister(task_t *pTask){
    MYSQL *db = pTask->db;
    char str[STR_LEN + 1] = {0};
    int i,flag;
    srand(time(NULL));//通过时间函数设置随机数种子，使得每次运行结果随机。
    for(i = 0; i < STR_LEN; i ++){

    flag = rand()%3;
    switch(flag){
            case 0:
            str[i] = rand()%26 + 'a';
            break;
            case 1:
            str[i] = rand()%26 + 'A';
            break;
            case 2:
            str[i] = rand()%10 + '0';
            break;
        }
    }
    printf("%s\n", str);//输出生成的随机数。
    sprintf(pTask->salt,"%s%s%s","$6$",str,"$");
    char *ciphertext = crypt(pTask->password,pTask->salt);
    char sql[300] = "insert into user(userName,salt,ciphertext) values('";
    strcat(sql,pTask->userName);
    strcat(sql,"','");
    strcat(sql,pTask->salt);
    strcat(sql,"','");
    strcat(sql,ciphertext);
    strcat(sql,"')");
    //sprintf(sql,"%s%s%s%s%s%s",pTask->userName,"','",pTask->salt,"','",ciphertext,"')");
    int qret = mysql_query(db,sql);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(db));
        exit(-1);
    }
    //mysql_close(db);
    char sql2[300] = {0};
    sprintf(sql2,"insert into file(fileName,preId,type,userName,phyAddress) values('%s',0,'d','%s','/%s');"
    ,pTask->userName,pTask->userName,pTask->userName);
    qret = mysql_query(db,sql2);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(db));
        exit(-1);
    }
}